package com.lujieni.dbsharding.simple.service;


import com.lujieni.dbsharding.simple.dao.OrderDao;
import com.lujieni.dbsharding.simple.po.OrderPO;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    /**
     * 这里123L在那个库的同一张表中已经存在，那么124L那条数据也会回滚
     *
     * 不支持因网络，硬件异常导致的跨库事务：例如：同一事务中，跨两个库更新，更新完毕后、未提交之前，第一个库宕机，则只有第二个库数据提交
     */
    @Transactional
    public void useTransaction(){

        OrderPO orderPO = new OrderPO();
        orderPO.setId(124L);
        orderPO.setPrice(new BigDecimal("50"));
        orderPO.setUserId(2L);
        orderPO.setStatus(1);
        orderDao.insert(orderPO);
        System.out.println("hello");

        orderPO = new OrderPO();
        orderPO.setId(123L);
        orderPO.setPrice(new BigDecimal("50"));
        orderPO.setUserId(3L);
        orderPO.setStatus(1);
        orderDao.insert(orderPO);
    }

    /**
     *
     * 不知道为啥，在整合seata的at模式的时候必须
     * 指定默认数据源为m1,不然回滚失效我也不到为啥！！！
     *
     */
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void useSeata(){

        OrderPO orderPO = new OrderPO();
        orderPO.setId(2L);
        orderPO.setPrice(new BigDecimal("50"));
        orderPO.setUserId(3L);
        orderPO.setStatus(1);
        orderDao.insert(orderPO);

        orderPO = new OrderPO();
        orderPO.setId(1L);
        orderPO.setPrice(new BigDecimal("50"));
        orderPO.setUserId(2L);
        orderPO.setStatus(1);
        orderDao.insert(orderPO);
        System.out.println("hello");



        int n = 5 / 0;
    }

}
